//
//  SLUserAccountViewModel.swift
//  0319iOSweiboDemo
//
//  Created by Tang on 16/3/22.
//  Copyright © 2016年 大天朝. All rights reserved.
//

import UIKit

//VM 专门负责模型的相关操作
class SLUserAccountViewModel: NSObject {
    
    //单例
    static let sharedInstance: SLUserAccountViewModel = SLUserAccountViewModel()
    
    private override init() {
        super.init()
        
        //从沙盒里面加载账号
       userAccount = loadUserAccount()
    }
    //保存账号
    var userAccount : SLUserAccount?
    
    //是否登录.只读计算性属性
    var userLogin: Bool {
        get {
            return userAccount != nil
        }
    }
    
    //获取用户信息
    func loadUserInfo(completion: (error: NSError?) -> ()) {
        //url
        let urlString = "https://api.weibo.com/2/users/show.json"
       
        //参数
//        let parameters: [String: AnyObject] = [
//            "access_token": userAccount!.access_token!,
//            "uid": userAccount!.uid!
//        ]
        //封装后
        let parameters: [String: AnyObject] = ["uid": userAccount!.uid!]
        
        SLNetworkTool.sharedInstance.requestGET(urlString, parameters: parameters) { (result, error) -> () in
            if error != nil {
                //出现错误
                completion(error: error)
                return
            }
            //给账号赋值
            self.userAccount?.screen_name = result?["screen_name"] as? String
            self.userAccount?.avatar_large = result?["avatar_large"] as? String
            
            //将账号新的数据保存到沙盒里面
            self.saveUserAccount()
        }
        
//        SLNetworkTool.sharedInstance.AFNManager.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
//            //成功
//            SLPrint(msg: "result: \(result)")
//            let dict = result as? [String: AnyObject]
//            //给账号赋值
//           self.userAccount?.screen_name = dict?["screen_name"] as? String
//           self.userAccount?.avatar_large = dict?["avatar_large"] as? String
//          
//            //将账号新的数据保存到沙盒里面
//            self.saveUserAccount()
//            completion(error: nil)
//            }) { (_, error) -> Void in//失败
//                SLPrint(msg: "error: \(error)")
//                completion(error: error)
//        }
    }
    
    
    //加载access_token
    func loadAccessToken(code: String,completion: (error: NSError?) -> ()) {
        //获取access_token的url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //拼接参数
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : grant_type,
            "code" : code,
            "redirect_uri" : redierct_url
        ]
        //发送请求
        SLNetworkTool.sharedInstance.requestPOST(urlString, parameters: parameters) { (result, error) -> () in
            if error != nil {//出错
                completion(error: error)
                return
            }
            self.userAccount = SLUserAccount(dict: result!)
                    print("userAccount: \(self.userAccount)")
                    //保存模型到沙盒
                    self.saveUserAccount()
            
                    //2.通知控制器保存完成
                    completion(error: nil)
            
        }
//        //发送请求
//       SLNetworkTool.sharedInstance.AFNManager.POST(urlString, parameters: parameters, progress: nil, success: { (_, response) -> Void in
//            print("response: \(response)")
//            //将accessToken保存起来.下次直接使用
//                if let dict = response as? [String: AnyObject] {
//                    //将网络返回的账号赋值给属性.别人直接访问
//                    self.userAccount = SLUserAccount(dict: dict)
//                    print("userAccount: \(self.userAccount)")
//                    //保存模型到沙盒
//                    self.saveUserAccount()
//                    
//                    //2.通知控制器保存完成
//                     completion(error: nil)
//                }
//            }) { (_, error) -> Void in
//                print("请求失败accessToken: \(error)")
//                //2.通知控制器出现了错误
//                completion(error: error)
//        }
    }
    //归档路径(账号路径)
    var accountPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccountPath.plist")
//    private let accountPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/userAccountPath.plist"))
    
    //保存账号信息
    private func saveUserAccount() {
        if userAccount != nil {//有账号才保存
            NSKeyedArchiver.archiveRootObject(userAccount!, toFile: accountPath)
        }
    }
    
    //从沙盒加载数据
    private func loadUserAccount() -> SLUserAccount? {
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? SLUserAccount
//        print("accountPath: \(accountPath)")
        //如果加载出账号.需要判断accessToken是否过期     .判断是否过期
        //userAccount?.expiresDate 和当前时间判断
        //userAccount?.expiresDate > NSDate()  表示没有过期
        //测试过期时间:1.修改模拟器时间  2. userAccount?.expiresDate? 重新赋值  3.让服务器返回一个过期时间
//        userAccount?.expiresDate? = NSDate(timeIntervalSinceNow: -1000)
        if userAccount != nil && userAccount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            print("userAccount: \(userAccount)")
            return userAccount
        }
        return nil
    }
}
